import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:nyh_motorcade_app/entity/driver_info_entity.dart';
import 'package:nyh_motorcade_app/http/http_address.dart';
import 'package:nyh_motorcade_app/http/http_manager.dart';
import 'package:nyh_motorcade_app/utils/sp_utils.dart';
import 'package:nyh_motorcade_app/utils/toast_utils.dart';
import 'package:nyh_motorcade_app/utils/verify_utils.dart';
import 'package:nyh_motorcade_app/widgets/multi_state/multi_state_widget.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class SearchDriverController extends GetxController {
  TextEditingController searchController = TextEditingController();
  FocusNode searchFocusNode = FocusNode();
  RefreshController refreshController = RefreshController();
  MultiState multiState = MultiState.loading;
  List<String> historyRecordList = [];
  List<DriverInfoItem> driverInfoList = [];
  int orderCount = 0;
  String keyword = "";
  int page = 1;

  @override
  void onReady() {
    super.onReady();
    getHistoryRecord();
  }

  @override
  void onClose() {
    SPUtils.saveStringList(SPUtils.SEARCH_DRIVER_HISTORY_RECORD, historyRecordList);
  }

  Future<void> getHistoryRecord() async {
    historyRecordList = await SPUtils.getStringList(SPUtils.SEARCH_DRIVER_HISTORY_RECORD);
    update();
  }

  void deleteHistoryRecord() {
    if (historyRecordList.isNotEmpty) {
      historyRecordList = [];
      SPUtils.saveStringList(SPUtils.SEARCH_DRIVER_HISTORY_RECORD, historyRecordList);
      update();
    }
  }

  void addHistoryRecord() {
    if (keyword.isEmpty) {
      return;
    }
    if (historyRecordList.contains(keyword)) {
      historyRecordList.remove(keyword);
    }
    if (historyRecordList.isEmpty) {
      historyRecordList.add(keyword);
    } else {
      if (historyRecordList.length >= 10) {
        historyRecordList.removeLast();
      }
      historyRecordList.insert(0, keyword);
    }
  }

  void searchVehicle(String value) {
    keyword = value;
    driverInfoList.clear();
    if (keyword.isEmpty) {
      update();
      return;
    } else {
      page = 1;
      multiState = MultiState.loading;
      update();
      getDriverInfoList();
    }
  }

  Future<void> onLoading() async {
    getDriverInfoList();
  }

  Future<void> getDriverInfoList() async {
    httpManager.post(
      Get.context,
      HttpAddress.GET_DRIVER_INFO_LIST,
      {
        "superId": await SPUtils.getString(SPUtils.COMPANY_ID),
        "belongingType": null,
        "motorcadeId": null,
        "name": VerifyUtils.isNumber(keyword) ? null : keyword,
        "phone": VerifyUtils.isNumber(keyword) ? keyword : null,
      },
      headers: {"page": page, "limit": 10},
      isToast: true,
      onSuccess: (data) {
        if (data == null) {
          ToastUtils.toast("请求失败");
          if (refreshController.isRefresh) {
            refreshController.refreshFailed();
          } else {
            refreshController.loadFailed();
          }
          if (page == 1) {
            multiState = MultiState.fail;
          }
          update();
          return;
        }
        DriverInfoEntity driverInfoEntity = DriverInfoEntity().fromJson(data);
        orderCount = driverInfoEntity.total ?? 0;
        List<DriverInfoItem> list = driverInfoEntity.item ?? [];
        if (list.isNotEmpty) {
          addHistoryRecord();
          multiState = MultiState.success;
          if (refreshController.isRefresh) {
            driverInfoList.clear();
            refreshController.refreshCompleted();
          } else {
            if (list.length >= 10 || page == 1) {
              refreshController.loadComplete();
            } else {
              refreshController.loadNoData();
            }
          }
          if (page == 1) {
            driverInfoList.clear();
          }
          driverInfoList.addAll(list);
          page++;
        } else {
          if (refreshController.isRefresh) {
            refreshController.refreshCompleted();
          } else {
            refreshController.loadNoData();
          }
          if (page == 1) {
            multiState = MultiState.empty;
          }
        }
        update();
      },
      onFail: (code, msg) {
        if (refreshController.isRefresh) {
          refreshController.refreshFailed();
        } else {
          refreshController.loadFailed();
        }
        if (page == 1) {
          multiState = MultiState.fail;
        }
        update();
      },
      onError: (msg) {
        if (refreshController.isRefresh) {
          refreshController.refreshFailed();
        } else {
          refreshController.loadFailed();
        }
        if (page == 1) {
          multiState = MultiState.error;
        }
        update();
      },
    );
  }
}
